package com.wechat.gateway.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wechat.gateway.config.WhitelistConfig;
import com.wechat.gateway.service.TokenService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * Token认证过滤器
 */
@Slf4j
@Component
public class TokenFilter extends AbstractGatewayFilterFactory<TokenFilter.Config> {

    @Autowired
    private TokenService tokenService;

    @Autowired
    private WhitelistConfig whitelistConfig;

    @Autowired
    private ObjectMapper objectMapper;

    public TokenFilter() {
        super(Config.class);
    }

    @Override
    public GatewayFilter apply(Config config) {
        return (exchange, chain) -> {
            ServerHttpRequest request = exchange.getRequest();
            String path = request.getURI().getPath();
            log.debug("Token过滤器处理请求: {}", path);
            // 检查是否在认证白名单中
            if (whitelistConfig.isAuthWhitelist(path)) {
                log.debug("路径 {} 在认证白名单中，跳过token验证", path);
                return chain.filter(exchange);
            }

            // 验证token
            Long userId = tokenService.getUserId(request);
            if (userId == null) {
                log.warn("未授权访问: {}", path);
                return handleUnauthorized(exchange.getResponse());
            }

            // Token验证成功，将用户信息添加到请求头
            ServerHttpRequest modifiedRequest = request.mutate()
                    .header("X-User-Id", String.valueOf(userId))
                    .header("X-Auth-Status", "authenticated")
                    .build();

            log.debug("Token验证成功，用户ID: {}", userId);

            return chain.filter(exchange.mutate().request(modifiedRequest).build());
        };
    }

    /**
     * 处理未授权响应
     */
    private Mono<Void> handleUnauthorized(ServerHttpResponse response) {
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);

        Map<String, Object> result = new HashMap<>();
        result.put("code", 401);
        result.put("message", "未授权访问，请先登录");
        result.put("timestamp", LocalDateTime.now());
        result.put("path", "gateway-auth-filter");

        try {
            String jsonResult = objectMapper.writeValueAsString(result);
            DataBuffer buffer = response.bufferFactory().wrap(jsonResult.getBytes(StandardCharsets.UTF_8));
            return response.writeWith(Mono.just(buffer));
        } catch (JsonProcessingException e) {
            log.error("序列化响应失败: {}", e.getMessage());
            DataBuffer buffer = response.bufferFactory().wrap("{\"code\":401,\"message\":\"未授权访问\"}".getBytes(StandardCharsets.UTF_8));
            return response.writeWith(Mono.just(buffer));
        }
    }

    /**
     * 配置类
     */
    @Data
    public static class Config {
        /**
         * 是否启用Token验证
         */
        private boolean enabled = true;

        /**
         * 自定义错误消息
         */
        private String errorMessage = "未授权访问，请先登录";
    }
}
